import React, { Component } from 'react';
import * as echarts from 'echarts';

class PieChart extends Component {
  constructor() {
    super();
    this.state = {};
  }

  componentDidMount() {
    const { id = 'pie' } = this.props;
    if (id) {
      this.chart = echarts.init(document.getElementById(id));
      this.setData(this.props);
    }
  }
  componentWillReceiveProps(nextProps) {
    nextProps.id && this.setData(nextProps);
    if (nextProps.height !== this.props.height || nextProps.width !== this.props.width) {
      console.log('resize');
      this.chart &&
        this.chart.resize({
          width: nextProps.width,
          height: nextProps.height,
        });
    }
  }

  setData = (props) => {
    const { title, dataSource, legendSetting = {}, colors } = props;
    const nameDatas = dataSource && dataSource.map((item) => item.name);

    this.chart.setOption({
      color: this.props.colorOptions || [
        '#c23531',
        '#2f4554',
        '#61a0a8',
        '#d48265',
        '#91c7ae',
        '#749f83',
        '#ca8622',
        '#bda29a',
        '#6e7074',
        '#546570',
        '#c4ccd3',
      ],

      tooltip: {
        trigger: 'item',
        formatter: '{b} : {c} ({d}%)',
      },
      legend: {
        orient: this.props.orient || 'vertical',
        left: this.props.left || 'right',
        data: nameDatas,
        textStyle: {
          color: colors ? colors[0] : '#333',
        },
        ...legendSetting,
      },
      series: {
        name: title,
        type: 'pie',
        data: dataSource,
        height: this.props.seriesHeight || 'auto',
        top: this.props.seriesTop || 0,
        bottom: this.props.seriesBottom || 0,
        avoidLabelOverlap: true,
        minAngle: 6,
        minShowLabelAngle: 30,
      },
    });
  };

  render() {
    const { width = 1000, height = 500, id } = this.props;
    return <div id={id} style={{ width: width, height: height }} />;
  }
}

export default PieChart;
